package main

import (
	"gitee.com/hlwqds/rabitmqTest/log"
	"github.com/streadway/amqp"
	syslog "log"
	"strconv"
)

func fib(n int) int {
	if n == 0 {
		return 0
	} else if n == 1{
		return 1
	} else {
		return fib(n-1) + fib(n-2)
	}
}

func main(){
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	log.FailOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	log.FailOnError(err, "Failed to open a channel")
	defer ch.Close()

	q, err := ch.QueueDeclare(
		"rpc_queue",
		false,
		false,
		false,
		false,
		nil)
	log.FailOnError(err, "Failed to declare a queue")

	err = ch.Qos(
		1,
		0,
		false)
	log.FailOnError(err, "Failed to set Qos")

	msgs, err := ch.Consume(
		q.Name,
		"",
		false,
		false,
		false,
		false,
		nil)
	log.FailOnError(err, "Failed to register a consumer")

	forever := make(chan bool)
	go func(){
		for d := range msgs {
			n, err := strconv.Atoi(string(d.Body))
			log.FailOnError(err, "Failed to convert body to integer")
			syslog.Printf(" [.] fib(%d)", n)
			response := fib(n)
			err = ch.Publish(
				"",
				d.ReplyTo,
				false,
				false,
				amqp.Publishing{
					ContentType: "text/plain",
					CorrelationId: d.CorrelationId,
					Body: []byte(strconv.Itoa(response)),
				})
			log.FailOnError(err, "Failed to publish a message")

			d.Ack(false)
		}
	}()
	syslog.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}